package com.xxx.dit.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.xxx.base.utils.R;
import com.xxx.dit.domain.Dict;
import com.xxx.dit.domain.DictItem;
import com.xxx.dit.query.DictQuery;
import com.xxx.dit.service.IDictService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/dict")
@Api(tags = "数据字典接口类")
public class DictController {

    @Autowired
    private IDictService dictService;

    @GetMapping
    @ApiOperation(value = "查询所有数据字典")
    public List<Dict> findAll() {
        return dictService.findAll();
    }

    @GetMapping("/{id}")
    @ApiOperation(value = "通过ID查询数据字典")
    public R<Dict> findOne(@PathVariable long id) {
        Dict dict = dictService.findOne(id);
        return R.ok(dict);
    }

    @PostMapping
    @ApiOperation(value = "分页加条件查询")
    public R<PageInfo<Dict>> queryPage(@RequestBody DictQuery dictQuery) {
        List<Dict> list = dictService.queryPage(dictQuery);
        PageHelper.startPage(dictQuery.getCurrentPage(), dictQuery.getPageSize());
        return R.ok(new PageInfo<Dict>(list));
    }

    @PutMapping
    @ApiOperation(value = "增加或者修改数据字典")
    public R<Void> updateAndAddDict(@RequestBody Dict dict) {
        try {
            Long id = dict.getId();

            if (id == null) {
                dictService.addDict(dict);
            } else {
                dictService.updateDict(dict);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return R.fail("数据字典名称已存在");
        }
        return R.ok();
    }

    @DeleteMapping("/{id}")
    @ApiOperation(value = "通过ID删除数据字典")
    public R<Void> deleteDict(@PathVariable long id) {
        try {
            dictService.deleteDict(id);
        } catch (Exception e) {
            e.printStackTrace();
            return R.fail();
        }
        return R.ok();
    }

    @PatchMapping
    @ApiOperation(value = "批量删除数据字典")
    public R<Void> batchDicts(@RequestBody long[] ids) {
        try {
            dictService.batchDicts(ids);
        } catch (Exception e) {
            e.printStackTrace();
            return R.fail();
        }
        return R.ok();
    }


}
